<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>登录</h2>
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="rules"
        @keyup.enter="handleLogin"
      >
        <FormErrorMessage 
          v-model="generalError"
          :is-general="true"
        />
        <el-form-item prop="email">
          <el-input 
            v-model.trim="loginForm.email" 
            placeholder="邮箱"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model.trim="loginForm.password" 
            type="password" 
            placeholder="密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>
        <div class="register-link">
          还没有账号？<router-link to="/register">立即注册</router-link>
        </div>
        <div class="reset-password-link">
          <router-link to="/reset-password">忘记密码？</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, inject } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, getUserInfo } from '@/api/user'
import { setToken, setEmail } from '@/utils/cookies'
import FormErrorMessage from '@/components/FormErrorMessage.vue'

const router = useRouter()
const loginFormRef = ref(null)
const updateLoginStatus = inject('updateLoginStatus')  

const generalError = ref('')  

const loginForm = reactive({
  email: '',
  password: ''
})

const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  try {
    generalError.value = ''  // 清除之前的错误
    await loginFormRef.value.validate()
    const res = await login(loginForm)
    // 保存token，使用后端返回的过期天数
    setToken(res.access, res.expires_in_days)
    // 获取用户信息并保存email，使用相同的过期天数
    const userInfo = await getUserInfo()
    setEmail(userInfo.email, res.expires_in_days)
    // 更新导航栏状态
    await updateLoginStatus()
    ElMessage.success('登录成功')
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
    // 设置错误消息
    generalError.value = error.response?.data?.detail || '登录失败，请检查邮箱和密码'
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.login-card {
  width: 100%;
  max-width: 400px;
}

.login-card h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
}

.register-link a {
  color: var(--el-color-primary);
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}

.reset-password-link {
  text-align: center;
  margin-top: 8px;
  font-size: 14px;
}

.reset-password-link a {
  color: var(--el-color-primary);
  text-decoration: none;
}

.reset-password-link a:hover {
  text-decoration: underline;
}
</style>